import React, { useEffect, useState } from 'react'
import { Input, Button, Modal, Select, message } from 'antd';
import { BaseListPage, IBaseListPageProps, IBaseListPageState, columnRenders, UdSelectAjax, http, uaaApp } from '../../../lib/index'
import { UdModal } from '../../../lib/ui/UdModal';
import './index.scss';
import apis from '@/apis/AnnouncementManage';
import ViewDetailContent from './component/ViewDetailModalContent'
import dayjs from 'dayjs';
import { downBlobFile } from '@/utils/methods'
import axios from 'axios'
import udMainStore from '@/store/UdMain'
import UdSelect from '@/components/UdFormControls/UdSelect'

interface IRepairListProps extends IBaseListPageProps { }

interface IRepairListState extends IBaseListPageState { }

const AddBtnAuth = 'customer_dealer_notice_manager_insert'
const UpdateBtnAuth = 'customer_dealer_notice_manager_update'
const DetailBtnAuth = 'customer_dealer_notice_manager_Notice'
const DeleteBtnAuth = 'customer_dealer_notice_manager_delete'
const DownloadBtnAuth = 'customer_dealer_notice_manager_downreadandunread'
const ReadandUnreadBtnAuth = 'customer_dealer_notice_manager_readandunread'
const ReturnBtnAuth = 'customer_dealer_notice_manager_withdrawNotice'

//接口字段映射
const fieldMap = {
  //标题
  title: "title",
  //状态
  status: "status",
  //公告分类
  classification: "noticeClassName",
  //发布人
  publisher: "publishBy",
  //所属销售组织
  salesOrganization: "brandName",
  //更新时间
  updateTime: "updatedTime",
  //浏览记录
  browseRecord: "browseRecord",
  //已读
  haveRead: "haveRead",
  //未读
  unRead: "unRead",
  // 已读列表
  haveReadList: "readUserNames",
  //未读列表
  unReadList: "unReadUserNames",
  //草稿
  draft: 0,
  //已发布
  published: 1,
  //撤回
  unpublished: 2
}

export default class AnnouncementManagementList extends BaseListPage<IRepairListProps, IRepairListState> {

  public brandList = udMainStore.brandList

  constructor(props: IRepairListProps) {
    super(props)
    //页面配置
    this.state = {
      //标题
      title: '公告管理',
      //表单请求地址
      queryApi: apis.getAnnouncementManagementList,
      method: 'GET',
      //搜索项配置
      conditions: [
        {
          label: '品牌公司',
          id: 'brandCode',
          // initialValue: this.brandList[0].value,
          render: (
            <UdSelect
              showSearch
              allowClear={true}
              options={this.brandList}
            />
          ),
        },
        {
          id: 'agentCode', label: '经销商编号',
          render: () => {
            return <Input />
          }
        },
        {
          id: 'agentName', label: '经销商名称',
          render: () => {
            return <Input />
          }
        },
        {
          id: fieldMap.title, label: '标题',
          render: () => {
            return <Input />
          }
        },
        {
          id: fieldMap.status, label: '状态', render: () => {
            return <Select>
              <Select.Option value={fieldMap.draft}>草稿</Select.Option>
              <Select.Option value={fieldMap.published}>已发布</Select.Option>
              <Select.Option value={fieldMap.unpublished}>已撤回</Select.Option>
            </Select>
          }
        },
        {
          id: "noticeClassId", label: '公告分类', render: () => {
            return <UdSelectAjax
              query={() => {
                return http.get(apis.getAllClassificationList)
              }}
              mapping={{ value: 'id', title: 'noticeClassName' }} />
          }
        }
      ],
      rowKey: (record, index) => index + "",
      //表格项配置
      columns: [
        ["标题", fieldMap.title],
        ["公告分类", fieldMap.classification],
        ["发布人", fieldMap.publisher],
        ["所属销售组织", fieldMap.salesOrganization],
        { title: "状态", key: fieldMap.status, render: (text, record, index) => this.renderStatus(record) },
        ["更新时间", fieldMap.updateTime],
        { title: "浏览记录", key: fieldMap.browseRecord, render: (text, record, index) => this.renderBrowseRecord(record) },
        //表格操作项配置
        {
          title: "操作",
          key: "dos",
          fixedWidth: '100px',
          render: columnRenders.operate([
            {
              title: '查看', auth: DetailBtnAuth, action: (text: any, record: any) => this.showDetails(record)
            },
            {
              title: "编辑", auth: UpdateBtnAuth, action: (text, record) => this.edit(record), show: (text: any, record: any, index: number) => record[fieldMap.status] === fieldMap.draft
            },
            {
              title: "删除", auth: DeleteBtnAuth, action: (text, record) => this.delete(record), show: (text: any, record: any, index: number) => record[fieldMap.status] !== fieldMap.published
            },
            {
              title: "撤回", auth: ReturnBtnAuth, action: (text, record) => this.withdraw(record), show: (text: any, record: any, index: number) => record[fieldMap.status] === fieldMap.published
            }
          ])
        }
      ],
      //页面操作项配置
      leftBtns: [
        uaaApp.canUse(AddBtnAuth) && <Button type="primary" onClick={() => { this.addNew() }}>发布公告</Button>
      ],
      tableProps: {
        rowSelection: null,
      }
    }
  }

  //新增
  private addNew = () => this.props.history.push('/AnnouncementManagement/List/AddNew')

  //查看详情
  private showDetails = (record: any) => {
    const { title } = record
    UdModal.open({
      title,
      content: <Deatils record={record} />,
      footer: null,
    })
  }

  //编辑
  private edit = (record: any) => this.props.history.push('/AnnouncementManagement/List/Edit/' + record.id)

  //删除 
  private delete = (record: any) => {
    console.log("删除公告:" + record)
    Modal.confirm({
      title: '删除公告',
      content: "公告删除后将无法恢复，是否继续？",
      okType: 'danger',
      onOk: () => {
        return http.post(apis.postDeleteAnnouncementManagament + "?id=" + record.id).then(res => {
          message.success('删除成功')
          this.query()
        })
      },
    });
  }

  //撤回
  private withdraw = (record: any) => {
    Modal.confirm({
      title: '撤回公告',
      content: "公告撤回后接受对象将无法查收，是否继续？",
      okType: 'danger',
      onOk: () => {
        return http.get(apis.getAnnouncementManagamentWithdraw, { params: { id: record.id } }).then(res => {
          message.success('撤回成功')
          this.query()
        })
      },
    });
  }

  //表格状态渲染
  private renderStatus = (record) => <><span style={{
    display: "inline-block",
    width: "6px",
    height: "6px",
    borderRadius: "6px",
    marginRight: "5px",
    marginBottom: "1px",
    backgroundColor: record[fieldMap.status] === fieldMap.draft ? "#BFBFBF" : record[fieldMap.status] === fieldMap.published ? "#00A854" : record[fieldMap.status] === fieldMap.unpublished ? "#D9001B" : ""
  }}></span><span>{
    record[fieldMap.status] === fieldMap.draft ? "草稿" : record[fieldMap.status] === fieldMap.published ? "已发布" : record[fieldMap.status] === fieldMap.unpublished ? "已撤回" : ""
  }</span></>

  //浏览记录渲染
  private renderBrowseRecord = (record) => <>
    {
      record[fieldMap.browseRecord] ? <>
        <div><span>已读：</span><span onClick={uaaApp.canUse(ReadandUnreadBtnAuth) ? () => { this.showBrowseRecord("haveRead", record) } : null} style={{ color: "#00c1de", cursor: "pointer" }}>{record[fieldMap.browseRecord][fieldMap.haveRead]}</span></div>
        <div><span>未读：</span><span onClick={uaaApp.canUse(ReadandUnreadBtnAuth) ? () => { this.showBrowseRecord("unRead", record) } : null} style={{ color: "#00c1de", cursor: "pointer" }}>{record[fieldMap.browseRecord][fieldMap.unRead]}</span></div>
      </> : <span> / </span>
    }
  </>

  //浏览记录详情
  private showBrowseRecord = (status: string, record: any) => {
    const footer = !uaaApp.canUse(DownloadBtnAuth) && { footer: null }
    UdModal.open({
      title: "浏览记录",
      content: <RecordContent record={record} status={status} />,
      okText: "下载已读列表",
      ...footer,
      onOk: () => {
        const params = { noticeId: record.id }
        return http.get(apis.getAnnouncementManagamentDownload, { params, responseType: 'arraybuffer' }).then(res => {
          if (!res.data.code) {
            const fileData = res.data
            downBlobFile(fileData, '公告浏览记录')
          }
        })
      }
    })
  }

}

//浏览记录详情内容组件
const RecordContent = (props) => {
  const [status, setStatus] = useState(props.status)
  return <div className="record-content-box">
    <div className="header">
      <span onClick={() => { setStatus('haveRead') }} style={status === "haveRead" ? { borderBottom: "1px solid #00c1de", color: "#00c1de" } : {}}>已读({props.record[fieldMap.browseRecord][fieldMap.haveRead]})</span>
      <span onClick={() => { setStatus('unRead') }} style={status === "unRead" ? { borderBottom: "1px solid #00c1de", color: "#00c1de" } : {}}>未读({props.record[fieldMap.browseRecord][fieldMap.unRead]})</span>
    </div>
    <div className="content">
      {
        status === fieldMap.haveRead ?
          props.record[fieldMap.browseRecord][fieldMap.haveReadList].map((item, index) => <span key={index}>{item}</span>) :
          props.record[fieldMap.browseRecord][fieldMap.unReadList].map((item, index) => <span key={index}>{item}</span>)
      }
    </div>
  </div>
}

//公告详情组件
const Deatils = (props) => {

  const [data, setData] = useState(null)

  useEffect(() => {
    getDetail()
  }, [props.record.id])

  const getDetail = () => {
    http.get(apis.getAnnouncementManagementDetails + "?id=" + props.record.id).then(res => {
      const data = res.data
      const { enclosure } = data
      if (enclosure && enclosure.url) { // 处理附件字段格式{url,name}
        const { url, enclosureName: name } = enclosure
        const fileData = {
          name,
          url,
        }
        data.enclosure = [fileData]
      }
      data.text = data.text?.replace(/data-src/g, 'src')
      data.updatedTime = data.updatedTime ? dayjs(data.updatedTime).format('YYYY-MM-DD HH:mm:ss') : ""
      setData(data)
    })
  }

  return <ViewDetailContent sendName={data?.sendUser} time={data?.updatedTime} annexFile={data?.enclosure} content={data?.text} />
}

